package com.jinzhi.jzapi.examination.task;

import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.jzapi.utils.CerSynthesisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.jzweb.utils.WithZoreUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Component
public class AutoAggJudgCerJob implements Job {

    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private CertificatesService certificatesService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private DictService dictService;
    @Autowired
    private OrganizationNewsService organizationNewsService;

    /**
     * 证书生成
     * @param jobExecutionContext
     */
    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("---------------------开始查询一年内所有考试批次信息ID---------------------");
        //查询一年内所有认证批次信息ID
        List<Map<Object, Object>> cbatchs = certificationBatchService.selDaysAll(365);
        if (cbatchs != null && cbatchs.size() > 0) {
            //获取当前年份后两位
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy");
            String year = format.format(date);
            String yearRe = year.substring(year.length() - 2);

            //获取背景图片
            Map map = new HashMap();
            map.put("name", "证书背景图");
            map.put("type", "cer_synthesis");
            String cerSynthesis = dictService.selDicBy(map);
            if(StringUtils.isNotBlank(cerSynthesis)){
                cerSynthesis = ValuesUtil.localUrl + cerSynthesis;
            }
            //获取电子公章
            map.clear();
            map.put("name", "金职电子公章");
            map.put("type", "electronic_seal");
            String electronicSeal = dictService.selDicBy(map);
            if(StringUtils.isNotBlank(electronicSeal)){
                electronicSeal = ValuesUtil.localUrl + electronicSeal;
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNow = sdf.format(new Date());
            //具体的年、月、日可利用substring截取
            //dateNow.substring(开始下标，结束下标),下标原则：从0开始，包前不包后
            String issueDate = dateNow.substring(0, 4) + "年" + dateNow.substring(5, 7) + "月" + dateNow.substring(8, 10) + "日";
            Calendar now = Calendar.getInstance();

            for (Map cmap : cbatchs) {
                //证书编号
                StringBuilder cerNumEnd = new StringBuilder();
                cerNumEnd.append("1");
                String cerLevel = "无级";
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(Long.parseLong(cmap.get("profileId").toString()));
                if (certificateProfileDO != null) {
                    if (certificateProfileDO.getName().equals("幼儿照护职业技能等级证书")) {
                        cerNumEnd.append("690005");
                    } else {
                        cerNumEnd.append("000000");
                    }

                    CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(Long.parseLong(cmap.get("newId").toString()));
                    if (certificateNewsDO != null) {
                        if (certificateNewsDO.getGrade().equals(0)) {
                            cerLevel = "高级";
                        } else if (certificateNewsDO.getGrade().equals(1)) {
                            cerLevel = "中级";
                        } else if (certificateNewsDO.getGrade().equals(2)) {
                            cerLevel = "初级";
                        }
                    }
                } else {
                    cerNumEnd.append("000000");
                }
                cerNumEnd.append("071");
                if (cerLevel.equals("高级")) {
                    cerNumEnd.append("35");
                } else if (cerLevel.equals("中级")) {
                    cerNumEnd.append("25");
                } else if (cerLevel.equals("初级")) {
                    cerNumEnd.append("15");
                } else {
                    cerNumEnd.append("05");
                }

                //查询某认证批次下所有考生信息
                List<StuSignUpDO> stuSignUpDOS = stuSignUpService.findByKv("cbatch_id", Long.parseLong(cmap.get("id").toString()));
                if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
                    for (StuSignUpDO stuSignUpDO : stuSignUpDOS) {
                        String cerNumbers = cerNumEnd.toString();
                        String orgProvince = (String) EhCacheUtil.get("province" + stuSignUpDO.getOrgId());
                        if (orgProvince == null) {
                            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(stuSignUpDO.getOrgId());
                            String proCode = selProvinceCode(organizationNewsDO.getProvince());
                            cerNumbers = cerNumbers + proCode + stuSignUpDO.getOrgNum() + yearRe;
                            if (StringUtils.isNotBlank(organizationNewsDO.getProvince())) {
                                EhCacheUtil.put("province" + stuSignUpDO.getOrgId(), organizationNewsDO.getProvince());
                            } else {
                                EhCacheUtil.put("province" + stuSignUpDO.getOrgId(), "");
                            }
                        }else{
                            String proCode = selProvinceCode(orgProvince);
                            cerNumbers = cerNumbers + proCode + stuSignUpDO.getOrgNum() + yearRe;
                        }
//                        String pointImg;//考核点印章
//                        Object assPointPrincipalImg = EhCacheUtil.get("assPointPrincipalImg" + stuSignUpDO.getOrgId());
//                        if (assPointPrincipalImg == null) {
//                            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(stuSignUpDO.getOrgId());
//                            pointImg = organizationNewsDO.getCachet();
//                            if (StringUtils.isNotBlank(organizationNewsDO.getCachet())) {
//                                EhCacheUtil.put("assPointPrincipalImg" + stuSignUpDO.getOrgId(), organizationNewsDO.getCachet());
//                            } else {
//                                EhCacheUtil.put("assPointPrincipalImg" + stuSignUpDO.getOrgId(), "");
//                            }
//                        }else{
//                            pointImg = assPointPrincipalImg.toString();
//                        }

                        boolean sture = false;
                        if (stuSignUpDO.getState().equals(6)) {
                            sture = true;
                        } else {
                            //查询单个考生的所有考试信息
                            List<StuSignUpDO> stuSignUpDOS1 = stuSignUpService.findByKv("user_id", stuSignUpDO.getUserId());
                            for (StuSignUpDO stuSignUpDO1 : stuSignUpDOS1) {
                                //如果在该证书等级的考试中，考生状态存在已过理论，且时间为一年内,返回true
                                if (stuSignUpDO1.getState().equals(6)) {
                                    CertificationBatchDO certificationBatchDO1 = certificationBatchService.selectById(stuSignUpDO1.getCbatchId());
                                    if (certificationBatchDO1 != null) {
                                        if (certificationBatchDO1.getNewsId().equals(Long.parseLong(cmap.get("newId").toString()))) {
                                            ExaminationBatchDO examinationBatchDO = examinationBatchService.findOneByKv("cbatch_id", certificationBatchDO1.getId(), "type", 0);
                                            if (examinationBatchDO != null) {
                                                long diff = (new Date()).getTime() - examinationBatchDO.getStartTime().getTime();//这样得到的差值是毫秒级别
                                                long days = diff / (1000 * 60 * 60 * 24);
                                                if (days <= 365) {
                                                    sture = true;
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                        }


                        if (sture) {
                            //查询该考生对应的考试成绩,且必须大于两门的成绩；
                            // 如果理论没过，则判断是否有近一年的理论合格成绩；再判断技能成绩是否通过，如通过，新增x证书信息，同时修改考生表的状态，以往的不管
                            List<ExaminationResultsDO> examinationResultsDOs = examinationResultsService
                                    .findByKv("cbatch_id", Long.parseLong(cmap.get("id").toString()), "stu_sign_id", stuSignUpDO.getId());
                            if (examinationResultsDOs != null && examinationResultsDOs.size() > 1) {
                                for (ExaminationResultsDO examinationResultsDO : examinationResultsDOs) {
                                    ExaminationBatchDO examinationBatchDO = examinationBatchService.selectById(examinationResultsDO.getEbatchId());
                                    //技能考试成绩判断
                                    if (examinationBatchDO.getType() == 1) {
                                        if (examinationResultsDO.getTotalScore() >= examinationBatchDO.getPassMark()) {
                                            CertificatesDO certificatesDO = new CertificatesDO();
                                            certificatesDO.setUserId(stuSignUpDO.getUserId());//会员id
                                            certificatesDO.setNewsId(Long.parseLong(cmap.get("newId").toString()));//证书信息id
                                            certificatesDO.setGetTime(new Date());
                                            certificatesDO.setQueries(0);//查询次数
                                            certificatesDO.setState(0);//默认正常
                                            if (cerLevel.equals("")) {
                                                certificatesDO.setCertificateName(certificateProfileDO.getName());//证书名称
                                            } else {
                                                certificatesDO.setCertificateName(certificateProfileDO.getName() + "(" + cerLevel + ")");//证书名称
                                            }

                                            int cerEnd = 0;
                                            //查询出该证书编号最大值
                                            String cerNumber = certificatesService.selCerNumber(cerNumbers);
                                            if (StringUtils.isNotBlank(cerNumber)) {
                                                cerEnd = Integer.parseInt(cerNumber.substring(cerNumber.length() - 5));
                                            }
                                            String cerEnds = cerNumbers + WithZoreUtil.frontCompWithZore(cerEnd + 1, 5);
                                            certificatesDO.setNumbers(cerEnds);

                                            //添加证书图片
                                            String imgUrl = null;
                                            String imgUrlNoSale = null;
                                            try {
                                                String url = stuSignUpDO.getPhoto().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
                                                imgUrl = CerSynthesisUtil.overlapImage(0,cerSynthesis, stuSignUpDO.getName(), url, stuSignUpDO.getIdNumber(), cerEnds, issueDate,
                                                        now.get(Calendar.YEAR) + "", (now.get(Calendar.MONTH) + 1) + "", cerLevel, electronicSeal,
                                                        "", "");
                                                imgUrlNoSale = CerSynthesisUtil.overlapImage(1,cerSynthesis, stuSignUpDO.getName(), url, stuSignUpDO.getIdNumber(), cerEnds, issueDate,
                                                        now.get(Calendar.YEAR) + "", (now.get(Calendar.MONTH) + 1) + "", cerLevel, electronicSeal,
                                                        "", "");
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                            //转换一下图片路径，将反斜杠替换掉
                                            String url = imgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                            String imgUrl1 = url.replace("\\", "/");
                                            certificatesDO.setImgUrl(imgUrl1);
                                            //转换一下图片路径，将反斜杠替换掉
                                            String url1 = imgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                            String imgUrl2 = url1.replace("\\", "/");
                                            certificatesDO.setImgUrlNosale(imgUrl2);
                                            boolean cerbbc = certificatesService.insert(certificatesDO);
                                            if (cerbbc) {
                                                stuSignUpDO.setState(7);//状态改为已出证书
                                                boolean sbc = stuSignUpService.updateById(stuSignUpDO);
                                                if (!sbc) {
                                                    log.info("--------认证批次：" + stuSignUpDO.getCbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
                                                }
                                            } else {
                                                log.info("--------认证批次：" + stuSignUpDO.getCbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的证书生成失败！");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    private String selProvinceCode(String province) {
        if (province.equals("北京市")) {
            return "11";
        } else if (province.equals("天津市")) {
            return "12";
        } else if (province.equals("上海市")) {
            return "31";
        } else if (province.equals("重庆市")) {
            return "50";
        } else if (province.equals("河北省")) {
            return "13";
        } else if (province.equals("河南省")) {
            return "41";
        } else if (province.equals("云南省")) {
            return "53";
        } else if (province.equals("辽宁省")) {
            return "21";
        } else if (province.equals("黑龙江省")) {
            return "23";
        } else if (province.equals("湖南省")) {
            return "43";
        } else if (province.equals("安徽省")) {
            return "34";
        } else if (province.equals("山东省")) {
            return "37";
        } else if (province.equals("新疆维吾尔自治区")) {
            return "65";
        } else if (province.equals("新疆生产建设兵团")) {
            return "66";
        } else if (province.equals("江苏省")) {
            return "32";
        } else if (province.equals("浙江省")) {
            return "33";
        } else if (province.equals("江西省")) {
            return "36";
        } else if (province.equals("湖北省")) {
            return "42";
        } else if (province.equals("广西壮族自治区")) {
            return "45";
        } else if (province.equals("甘肃省")) {
            return "62";
        } else if (province.equals("山西省")) {
            return "14";
        } else if (province.equals("内蒙古自治区")) {
            return "15";
        } else if (province.equals("陕西省")) {
            return "61";
        } else if (province.equals("吉林省")) {
            return "22";
        } else if (province.equals("福建省")) {
            return "35";
        } else if (province.equals("贵州省")) {
            return "52";
        } else if (province.equals("广东省")) {
            return "44";
        } else if (province.equals("青海省")) {
            return "63";
        } else if (province.equals("西藏自治区")) {
            return "54";
        } else if (province.equals("四川省")) {
            return "51";
        } else if (province.equals("宁夏回族自治区")) {
            return "64";
        } else if (province.equals("海南省")) {
            return "46";
        } else if (province.equals("台湾省")) {
            return "71";
        } else if (province.equals("香港特别行政区")) {
            return "81";
        } else if (province.equals("澳门特别行政区")) {
            return "82";
        } else {
            return "00";
        }
    }


}
